﻿#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion

#region Using directives

using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using ZO.SmartCore.Core;
using ZO.SmartCore.Helpers;
using ZO.SmartCore.My4CSharp;
using ZO.SmartCore.Plugins;
using ZO.SmartCore.Windows.Forms;
using ZO.SmartMessenger.Plugins;

#endregion

namespace ZO.SmartMessenger.UI
{
    /// <summary>
    /// Main Form for Smart Messenger
    /// </summary>
    public partial class MainForm : SmartMainForm
    {

        #region Delegates

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MainForm"/> class.
        /// </summary>
        public MainForm()
        {
            InitializeComponent();


            PluginAssembly.Loading += new EventHandler<PluginEventArgs>(PluginAssembly_Loading);
            ProtocolPluginCollection.ProtocolPluginConnecting += new EventHandler(ProtocolPluginList_ProtocolConnecting);

            ProtocolPluginCollection.ProtocolPluginConnectCompleted += new EventHandler(ProtocolPluginList_ProtocolConnectCompleted);


            That.Application.Load += new EventHandler(Application_Load);

            segeoUISmall = FontHelper.GetFont("Segoe UI", 8.25F, FontStyle.Regular);


            this.MainMenuStrip.Font = segeoUISmall;
            

        }

   

        #endregion

        #region Destructor
        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="T:SmartMessenger.UI.MainForm"/> is reclaimed by garbage collection.
        /// </summary>
        ~MainForm()
        {
            PluginAssembly.Loading -= new EventHandler<PluginEventArgs>(PluginAssembly_Loading);

        }
        #endregion


        #region Fields

        private Font segeoUISmall;


        #endregion



        #region Methods


        /// <summary>
        /// Handles the Load event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void Application_Load(object sender, EventArgs e)
        {
            this.IMNotifyIcon.Visible = true;
            this.Left = That.Computer.Screen.WorkingArea.Width - this.Width - 80;
            this.Top = That.Computer.Screen.WorkingArea.Top + 20;

            LoadAccounts();
        }

        /// <summary>
        /// Handles the Shown event of the MainForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void MainForm_Shown(object sender, EventArgs e)
        {
            LoginForm form = new LoginForm();
            form.ShowDialog(this);
        }

        /// <summary>
        /// Handles the ProtocolConnectCompleted event of the ProtocolPluginList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void ProtocolPluginList_ProtocolConnectCompleted(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                this.Invoke(new SetStatusDelegate(this.SetStatus), "Connected");
            }
            else
            {
                this.SetStatus("Connected");
            }
        }

        /// <summary>
        /// Handles the ProtocolConnecting event of the ProtocolPluginList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void ProtocolPluginList_ProtocolConnecting(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                this.Invoke(new SetStatusDelegate(this.SetStatus), "Connecting");
            }
            else
            {
                this.SetStatus("Connecting");
            }
        }


        /// <summary>
        /// Sets the status.
        /// </summary>
        /// <param name="text">The text.</param>
        private void SetStatus(string text)
        {
            //this.IMToolStripStatusLabel.Text = text;
            //MessageBox.Show(text);
        }




        /// <summary>
        /// Handles the Loading event of the PluginAssembly.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:SmartCore.Plugins.PluginEventArgs"/> instance containing the event data.</param>
        private void PluginAssembly_Loading(object sender, PluginEventArgs e)
        {
            IPlugin plugin = (IPlugin)e.Plugin.GetPluginInterface();

            if (plugin != null)
            {
                string msg = String.Empty;

                if (plugin.Type == PluginType.Protocol)
                {
                    msg = StringHelper.Format("Loading {0}", e.Plugin.Name);
                }

                this.BeginInvoke((ThreadStart)delegate { this.OnLoadingModule(msg); });
            }
        }

        /// <summary>
        /// Handles the Click event of the aboutToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutForm().ShowDialog(this);
        } // Form1



        /// <summary>
        /// Loads the modules in background Thread.
        /// </summary>
        /// <remarks>Use The Invoke method to call method in proper thread</remarks>
        protected override void LoadModules()
        {

            this.BeginInvoke((ThreadStart)delegate { this.OnLoadingModule("Loading Plugins"); }); 


            PluginManager.LoadFromFolder(Path.Combine(That.Application.ExecutablePath, "Plugins"),
                "SmartMessenger.Plugin.*.dll", typeof(IPlugin), false, false, false);

            foreach (Plugin var in PluginManager.LoadedPlugins)
            {
                IPlugin plugin = (IPlugin)var.GetPluginInterface();

                if(plugin == null) continue;
                
                if (plugin.Type == PluginType.Protocol)
                {
                    //only add 
                    if (!MessengerHelper.ProtocolPlugins.Contains(plugin.ID))
                    {
                        //ProtocolPlugin plugin2 = (ProtocolPlugin)var.GetPluginInterface();

                        MessengerHelper.ProtocolPlugins.Add(plugin.ID, (ProtocolPlugin)plugin);

                    }
                }
            }




            if (InvokeRequired)
            {
                this.Invoke(new SimpleCaller(base.LoadModules));
            }
            else
            {
                base.LoadModules();
            }


        }



        /// <summary>
        /// Override This Method To Dispose Unmanaged Resources.
        /// </summary>
        protected override void DisposeManagedResources()
        {
            ProtocolPluginCollection.ProtocolPluginConnecting -= new EventHandler(ProtocolPluginList_ProtocolConnecting);

            ProtocolPluginCollection.ProtocolPluginConnecting -= new EventHandler(ProtocolPluginList_ProtocolConnectCompleted);
            MessengerHelper.DisposeThis();
            MessengerHelper.ProtocolPlugins.Clear();
            PluginManager.UnloadAll();
            base.DisposeManagedResources();
        }

        /// <summary>
        /// Handles the Tick event of the ProgressTimer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void ProgressTimer_Tick(object sender, EventArgs e)
        {
            //if (IMStatusToolStripProgressBar.Value < IMStatusToolStripProgressBar.Maximum)
            //{
            //    IMStatusToolStripProgressBar.PerformStep();
            //}
            //else
            //{

            //    IMStatusToolStripProgressBar.Value = IMStatusToolStripProgressBar.Minimum;
            //}
        }


        /// <summary>
        /// Handles the Click event of the AccountManagerToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void AccountManagerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AccountManager manager = new AccountManager();

            manager.ShowDialog(this);

            if (manager.DialogResult == DialogResult.OK)
            {
                LoadAccounts();
            }

        }


        private void LoadAccounts()
        {
            this.SuspendLayout();
            this.MainToolStripContainer.SuspendLayout();


            foreach (Account account in MessengerHelper.Accounts)
            {
                if (account.Login)
                    continue;

                  if (account.Protocol == null) continue;

                  string text = account.AccountName + " (" + account.Protocol.ProtocolName + ")";

              ToolStripMenuItem item = new ToolStripMenuItem(text);
                item.Font = segeoUISmall;


                this.SignInToolStripMenuItem.DropDownItems.Add(item);
            }

            this.MainToolStripContainer.ResumeLayout(false);

            this.ResumeLayout(false);

        }




        /// <summary>
        /// Handles the Click event of the ExitToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }







        #endregion









    } // class Form1
}